package com.mypog;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
@WebServlet("/Enemy")
public class Enemy extends HttpServlet {

	// BlockingQueue for long-polling.
	private static final List<BlockingQueue<String>> msgQueues = new ArrayList<BlockingQueue<String>>();
	private static int idNumbers = 0;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Response.
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		// Get user session.
		HttpSession session = request.getSession();
		String playerName = (String) session.getAttribute("username");

		// Get player and his enemy objects.
		AllUsers allusers = new AllUsers();
		User player = allusers.getUserObject(playerName, "user");
		User freeEnemy = allusers.getUserObject(playerName, "enemy");

		if (player != null) {
			if (player.getEnemy().equals("")) {
				if (freeEnemy != null) {

					// Player gets free enemy to play with.
					setUserAndEnemy(player, freeEnemy);

					// Response.
					out.print(player.getEnemy() + "," 
							+ player.isMyTurn() + ","
							+ player.getChangeId() + ","
							+ player.getHitOrMiss() + ","
							+ player.getSquareCounterPlayer());
				} 
			} else {
				// Response if players are already playing.
				try {
					BlockingQueue<String> q = msgQueues.get(player.getId());
					out.print(q.take());
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
			}
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// Response.
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();

		// Get user session.
		HttpSession session = request.getSession();
		String playerName = (String) session.getAttribute("username");

		// Get player and his enemy objects.
		AllUsers allusers = new AllUsers();
		User player = allusers.getUserObject(playerName, "user");
		User enemy = allusers.playingUsersEnemy(playerName);

		// Square id to see if there is a ship or not.
		int id = Integer.parseInt(request.getParameter("shipId"));

		// Set turns.
		player.setMyTurn(false);
		enemy.setMyTurn(true);
		
		// Control the square id for ships.
		// If value == 1, it's a hit.
		if (enemy.getShip(id) == 1) {
			enemy.setChangeId(id);
			enemy.setSquareCounterPlayer(enemy.getSquareCounterPlayer() - 1);
			enemy.setHitOrMiss("hit");
			
			setEnemyResponse(enemy);
		} else {
			enemy.setChangeId(id);
			enemy.setHitOrMiss("miss");
			
			setEnemyResponse(enemy);
		}
		// Send a response to the user.
		out.print(enemy.getShip(id));
	}
	
	// Response to enemy.
	private void setEnemyResponse(User freeEnemy) {
		try {
			msgQueues.get(freeEnemy.getId()).put(
							freeEnemy.getEnemy() + "," 
							+ freeEnemy.isMyTurn() + ","
							+ freeEnemy.getChangeId() + ","
							+ freeEnemy.getHitOrMiss() + ","
							+ freeEnemy.getSquareCounterPlayer());
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}

	// Set the player and his enemy values.
	private void setUserAndEnemy(User player, User freeEnemy) {
		freeEnemy.setEnemy(player.getName());
		freeEnemy.setMyTurn(false);
		freeEnemy.setId(idNumbers + 1);

		player.setMyTurn(true);
		player.setEnemy(freeEnemy.getName());
		player.setId(idNumbers);

		idNumbers += 2;
		msgQueues.add(new ArrayBlockingQueue<String>(100));
		msgQueues.add(new ArrayBlockingQueue<String>(100));

		setEnemyResponse(freeEnemy);
	}
}
